package com.spel.validate.service;

import com.spel.core.context.ContextHolder;
import com.spel.vo.LoginUser;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * @title: AuthService
 * @Author xu-xiang
 * @Date: 2024/1/29 17:23
 * @description: 验证方法bean, 验证失败 不抛错
 */
@Service
public class ValidateService {

    /**
     * 判断角色是否具有接口权限
     *
     * @param permission 权限编号,对应菜单的MENU_CODE
     * @return {boolean}
     */
    public boolean hasPermission(String permission) {

        // 模拟获取当前用户权限
        LoginUser loginUser = ContextHolder.get("loginUser", LoginUser.class);
        Assert.notNull(loginUser, "请先登录!");

        if (loginUser.getPermissionList().contains(permission)) {
            return true;
        }

        return false;
    }

    /**
     * 放行所有请求
     *
     * @return {boolean}
     */
    public boolean permitAll() {
        return true;
    }

    /**
     * 只有超管角色才可访问
     *
     * @return {boolean}
     */
    public boolean isSuperAdmin() {
        //查询当前用户是否为超管
        LoginUser loginUser = ContextHolder.get("loginUser", LoginUser.class);
        Assert.notNull(loginUser, "请先登录!");

        if (loginUser.isAdmin()) {
            return true;
        }

        return false;
    }

    /**
     * 是否已登录
     *
     * @return {boolean}
     */
    public boolean hasLogin() {
        Object loginUser = ContextHolder.get("loginUser", Object.class);
        if (loginUser instanceof LoginUser) {
            return true;
        }

        return false;
    }

    /**
     * 是否有时间授权
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return {boolean}
     */
    public boolean hasTimeAuth(Integer start, Integer end) {
        int hour = LocalDateTime.now().getHour();
        if (hour >= start && hour <= end) {
            return true;
        }

        return false;
    }

    /**
     * 判断是否有该角色权限
     *
     * @param role 单角色
     * @return {boolean}
     */
    public boolean hasRole(String role) {
        LoginUser loginUser = ContextHolder.get("loginUser", LoginUser.class);
        Assert.notNull(loginUser, "请先登录!");

        if (loginUser.getRoleList().contains(role)) {
            return true;
        }

        return false;
    }

    /**
     * 判断是否具有所有角色权限
     *
     * @param role 角色集合
     * @return {boolean}
     */
    public boolean hasAllRole(String... role) {
        LoginUser loginUser = ContextHolder.get("loginUser", LoginUser.class);
        Assert.notNull(loginUser, "请先登录!");

        Set<String> roleSet = new HashSet<>(loginUser.getRoleList());
        for (String r : role) {
            if (!roleSet.contains(r)) {
                return false;
            }
        }

        return true;
    }
}
